package com.chenxin.wms.controller;

import com.chenxin.common.annotation.Log;
import com.chenxin.common.constant.WmsConstants;
import com.chenxin.common.core.controller.BaseController;
import com.chenxin.common.core.domain.AjaxResult;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.core.page.TableDataInfo;
import com.chenxin.common.enums.BusinessType;
import com.chenxin.common.exception.wms.WmsException;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.common.utils.poi.ExcelUtil;
import com.chenxin.wms.domain.ObMasterEntity;
import com.chenxin.wms.domain.dto.ObMasterOperateParams;
import com.chenxin.wms.domain.vo.ObMasterVO;
import com.chenxin.wms.process.outbound.IProcWorkOrderOut;
import com.chenxin.wms.service.IObMasterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 生产出库单Controller
 *
 * @author gry
 * @date 2025-04-13
 */
@RestController
@RequestMapping("/wms/obMaster")
public class ObMasterController extends BaseController {
    @Autowired
    private IObMasterService obMasterService;
    @Autowired
    private IProcWorkOrderOut procWorkOrderOut;

    /**
     * 查询生产出库单列表
     */
    @PreAuthorize("@ss.hasPermi('wms:obMaster:list')")
    @GetMapping("/list")
    public TableDataInfo list(ObMasterVO obMasterVo) {
        startPage();
        List<ObMasterVO> list = obMasterService.selectObMasterList(obMasterVo);
        return getDataTable(list);
    }

    /**
     * 导出生产出库单列表
     */
    @PreAuthorize("@ss.hasPermi('wms:obMaster:export')")
    @Log(title = "生产出库单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ObMasterVO obMasterVo) {
        List<ObMasterVO> list = obMasterService.selectObMasterList(obMasterVo);
        ExcelUtil<ObMasterVO> util = new ExcelUtil<>(ObMasterVO.class);
        util.exportExcel(response, list, "生产出库单数据");
    }

    /**
     * 获取生产出库单详细信息
     */
    @PreAuthorize("@ss.hasPermi('wms:obMaster:query')")
    @GetMapping(value = {"/", "/{obMasterId}"})
    public AjaxResult getInfo(@PathVariable(value = "obMasterId", required = false) Long obMasterId) {
        AjaxResult ajax = AjaxResult.success();
        return ajax;
    }

    /**
     * 新增生产出库单
     */
    @PreAuthorize("@ss.hasPermi('wms:obMaster:add')")
    @Log(title = "新增出库单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ObMasterEntity obMasterEntity) {
        return success("新增主单成功!");
    }

    /**
     * 修改生产出库单
     */
    @PreAuthorize("@ss.hasPermi('wms:obMaster:edit')")
    @Log(title = "生产出库单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ObMasterEntity obMasterEntity) {
        return toAjax(obMasterService.updateObMaster(obMasterEntity));
    }

    /**
     * 删除生产出库单
     */
    @PreAuthorize("@ss.hasPermi('wms:obMaster:remove')")
    @Log(title = "生产领料单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{obMasterIds}")
    public AjaxResult remove(@PathVariable Long[] obMasterIds) {
        return toAjax(obMasterService.deleteObMasterByObMasterIds(obMasterIds, getUserId(), getUsername()));
    }

    @PostMapping("/workOrderOut")
    public AjaxResult workOrderOut(@RequestBody ObMasterOperateParams params) {
        if (StringUtils.isNull(params)) {
            return error("出库发料失败!出库内容不能为空!");
        }
        // 获取出库主单ids
        List<Long> obMasterIds = params.getObMasterIds();
        if (StringUtils.isNull(obMasterIds) || obMasterIds.size() == 0) {
            return error("出库发料失败!出库主单ID不能为空!");
        }
        // 定义提示消息
        StringBuilder message = new StringBuilder();
        int successCount = 0;
        // 循环处理obMasterIds
        for (Long obMasterId : obMasterIds) {
            try {
                ProcResult result = procWorkOrderOut.call(obMasterId, params.getCreator());
                message.append(result.getMessage());
                if (WmsConstants.PROC_SUCCESS.equals(result.getCode())) {
                    successCount++;
                }
            } catch (WmsException e) {
                message.append(e.getMessage());
            }
        }
        // 只要有一条主单成功，则返回成功
        if (successCount > 0) {
            return AjaxResult.success(message);
        } else {
            return AjaxResult.error(String.valueOf(message));
        }
    }

    @PreAuthorize("@ss.hasPermi('wms:obMaster:stock-prepare')")
    @Log(title = "出库备货", businessType = BusinessType.UPDATE)
    @PostMapping("/obStockPrepare")
    public AjaxResult obStockPrepare(@RequestBody ObMasterOperateParams dto) {
        if (StringUtils.isNull(dto)) {
            return error("出库备货失败!备货内容不能为空!");
        }
        // 获取备货主单ids
        List<Long> obMasterIds = dto.getObMasterIds();
        if (StringUtils.isNull(obMasterIds)) {
            return error("出库备货失败!备货主单ID不能为空!");
        }
        ProcResult result = obMasterService.operateObMasterByIds(obMasterIds, WmsConstants.STOCK_PREPARE, getUserId());
        if (WmsConstants.PROC_SUCCESS.equals(result.getCode())) {
            return AjaxResult.success(result.getMessage());
        }
        return AjaxResult.error(result.getMessage());
    }

    @PreAuthorize("@ss.hasPermi('wms:obMaster:stock-cancel')")
    @Log(title = "备货取消", businessType = BusinessType.UPDATE)
    @PostMapping("/obPrepareCancel")
    public AjaxResult obPrepareCancel(@RequestBody ObMasterOperateParams dto) {
        if (StringUtils.isNull(dto) || StringUtils.isEmpty(dto.getObMasterIds())) {
            return error("出库备货取消失败!备货主单ID不能为空!");
        }
        ProcResult result = obMasterService.operateObMasterByIds(dto.getObMasterIds(), WmsConstants.PREPARE_CANCEL, getUserId());
        if (WmsConstants.PROC_SUCCESS.equals(result.getCode())) {
            return AjaxResult.success(result.getMessage());
        }
        return AjaxResult.error(result.getMessage());
    }

    @PreAuthorize("@ss.hasPermi('wms:obMaster:obExecute')")
    @Log(title = "出库执行", businessType = BusinessType.UPDATE)
    @PostMapping("/obExecute")
    public AjaxResult obExecute(@RequestBody ObMasterOperateParams dto) {
        if (StringUtils.isNull(dto)) {
            return error("出库执行失败!出库主单ID不能为空!");
        }
        return AjaxResult.success();
    }
}
